import { firstLowerCase, firstUpperCase } from '../data/generator-html';

const definitionsMap = {};
const summaryMap = {};
const schemaMap = {};
const ignoreApi = ['page', 'list', 'create', 'update', 'view', 'delete', 'deleteAll'];
let apiList = [];
const subInterfaceList = [];

/**
 * 获取swagger数据
 * @param parseSwagger swagger数据
 * @param matchUrl 需要匹配的url
 */
export const getSwaggerData = (parseSwagger, matchUrl: string) => {
  if (!Object.keys(parseSwagger).length) {
    return '';
  }
  apiList = [];
  getDefinitionsMap(parseSwagger.definitions);
  getSchemaMap(parseSwagger.paths);
  // 获取url
  const urlKeyMap = Object.keys(parseSwagger.paths);
  for (let i = 0; i < urlKeyMap.length; i++) {
    const urlKey = urlKeyMap[i];
    if (urlKey.indexOf(matchUrl) > -1) {
      const apiMap = {
        url: urlKey,
        originUrl: urlKey,
        method: getMethod(parseSwagger.paths[urlKey]),
        summary: summaryMap[urlKey],
        description: '',
        parameters: {},
        isUpload: false,
        isDownload: !parseSwagger.paths[urlKey][getMethod(parseSwagger.paths[urlKey])].responses[200].schema,
      };
      if (parseSwagger.paths[urlKey][getMethod(parseSwagger.paths[urlKey])].consumes) {
        if (parseSwagger.paths[urlKey][getMethod(parseSwagger.paths[urlKey])].consumes[0] === 'multipart/form-data') {
          apiMap.isUpload = true;
        }
      }
      if (definitionsMap[schemaMap[urlKey]]) {
        for (const o in definitionsMap[schemaMap[urlKey]].properties) {
          if (definitionsMap[schemaMap[urlKey]].properties[o]) {
            if (definitionsMap[schemaMap[urlKey]].properties[o].type) {
              if (definitionsMap[schemaMap[urlKey]].properties[o].type === 'array') {
                if (definitionsMap[schemaMap[urlKey]].properties[o].items.$ref) {
                  definitionsMap[schemaMap[urlKey]].properties[o] =
                    definitionsMap[definitionsMap[schemaMap[urlKey]].properties[o].items.$ref.replace('#/definitions/', '')];
                }
              }
            }
          }
        }
        apiMap.parameters = definitionsMap[schemaMap[urlKey]].properties;

      } else {
        apiMap.parameters = schemaMap[urlKey];
      }
      if (parseSwagger.paths[urlKey][getMethod(parseSwagger.paths[urlKey])].description) {
        apiMap.description = parseSwagger.paths[urlKey][getMethod(parseSwagger.paths[urlKey])].description;
      }
      apiList.push(apiMap);
    }
  }
  return generatorApiCode();
};

/**
 * 生成service.ts的请求代码
*/
const generatorApiCode = () => {
  let serviceCode = '';
  apiList.map(item => {
    const lastWord = getLastPathWord(item.url);
    if (!ignoreApi.includes(lastWord)) {
      serviceCode += generatorServiceCode(item, lastWord);
    }
  });
  return serviceCode;
};

/**
 * 生成component.ts的方法代码
 */
export const generatorComponentMethod = () => {
  console.log(apiList);
  let methodCode = '';
  apiList.map(item => {
    const param = Object.keys(item.parameters || {});
    const lastWord = getLastPathWord(item.originUrl);
    if (ignoreApi.includes(lastWord)) {
      return;
    }
    item.url = item.originUrl;
    if (item.isUpload) {
      methodCode += `
/**
 * ${item.summary}
 */
${firstLowerCase(generatorGroupName(item))}() {
  // 模板下载地址
  const downUrl = \`\${HTTP_BASE_URL}\${SERVERS_NAME.XXX_XXX}${item.url}\`;
  const modal = this.modalService.create({
    nzTitle: '',
    nzContent: ImportModalComponent,
    nzMaskClosable: false,
    nzComponentParams: {
      downFileUrl: downUrl,
      fileList: [],
    },
    nzFooter: [
      {
        label: '取消',
        type: 'default',
        onClick: () => modal.destroy()
      },
      {
        label: '确定',
        type: 'primary',
        onClick: (componentInstance) => {
          const fileArry = componentInstance.fileList || [];
          if (!fileArry || fileArry.length === 0) {
            this.message.warning('请选择上传文件!');
            return;
          }
          const formData = new FormData();
          fileArry.forEach((file: any) => {
            formData.append('file', file);
          });
          // 执行导入
          this.http.${firstLowerCase(generatorGroupName(item))}Api(formData).subscribe(res => {
            if (res.status === StatusEnum.SUCCESS) {
              this.message.success(res.message);
              this.page(this.pageInfo);
              modal.destroy();
            }
          });
        }
      },
    ]
  });
}
`;
    } else if (item.isDownload && param.includes('pager')) {
      // 是分页下载，什么都不做
    } else if (item.isDownload && item.method === 'get' && !param.includes('pager')) {
      // 不是分页下载
      methodCode += `
/**
 * ${item.summary}
 */
get${getUrlTwoLastWord(item)}() {
  window.open(\`\${HTTP_BASE_URL}\${SERVERS_NAME.XXX_XXX}${item.url}\`, '_blank');
}
`;
    } else if (item.originUrl.indexOf('{') > -1) {
      const index = item.url.indexOf('{');
      const lastIndex = item.url.lastIndexOf('}');
      const dynamicParam = item.url.slice(index + 1, lastIndex);
      item.url = item.url.substring(0, index);
      methodCode += `
/**
 * ${item.summary}
 */
get${firstUpperCase(lastWord.replace('{', '').replace('}', ''))}() {
  this.http.get${firstUpperCase(lastWord.replace('{', '').replace('}', ''))}Api(${dynamicParam}).subscribe(res => {
    if (res.status === StatusEnum.SUCCESS) {
      console.log(res);
    }
  });
}
`;
    } else {
      methodCode += `
/**
 * ${item.summary}
 */
${hasGetWord(item)}${hasGetWord(item) ? generatorGroupName(item) : firstLowerCase(generatorGroupName(item))}() {
  this.http.${hasGetWord(item)}${hasGetWord(item) ? generatorGroupName(item) : firstLowerCase(generatorGroupName(item))}Api(${generatorInterfaceParam(item, lastWord)}).subscribe(res => {
    if (res.status === StatusEnum.SUCCESS) {
      console.log(res);
    }
  });
}
`;
    }
  });
  return methodCode;
};

/**
 * 生成component.ts的接口代码
 */
export const generatorComponentInterface = () => {
  let interfaceCode = '';
  apiList.map(item => {
    if (!item.parameters) {
      return;
    }
    const param = Object.keys(item.parameters);
    if (param.length === 1 && param[0] === 'id') {
      return;
    }
    const lastWord = getLastPathWord(item.originUrl);
    const ignoreList = ignoreApi.filter((ele: string) => !['create', 'update'].includes(ele));
    if (ignoreList.includes(lastWord)) {
      return;
    }
    // 过滤分页导出
    if (param.length === 3 && param.includes('pager') && param.includes('mode') && param.includes('sourceIds')) {
      return;
    }
    interfaceCode += `
/**
 * ${item.summary}
 */
interface I${generatorGroupName(item)} {
  ${generatorInterfaceField(item)}
}
`;
    });
  const fieldList = [];
  const subInterfaceDataList = [];
  subInterfaceList.map(ele => {
    if (!fieldList.includes(ele.field)) {
      fieldList.push(ele.field);
      subInterfaceDataList.push(ele);
    }
  });
  subInterfaceDataList.map(ele => {
    interfaceCode += `
/**
 * ${ele.title}
 */
interface I${firstUpperCase(ele.field)} {
  ${generatorInterfaceField(ele)}
}
`;
  });
  return interfaceCode;
};


/**
 * 生成service.ts的请求代码
 */
const generatorServiceCode = (data: any, lastWord) => {
  if (data.isUpload) {
    return `
/**
 * ${data.summary}
 */
${firstLowerCase(generatorGroupName(data))}Api(data: any) {
  return this.http.postFile(data, \`\${this.preUrl}${lastWord}\`);
}
`;
  }
  const param = Object.keys(data.parameters || {});
  // 是分页下载
  if (data.isDownload && param.includes('pager')) {
    return '';
  }
  // 不是分页下载
  if (data.isDownload && data.method === 'get' && !param.includes('pager')) {
    return '';
  }
  if (data.originUrl.indexOf('{') > -1) {
    data.url = data.originUrl;
    const index = data.originUrl.indexOf('{');
    const lastIndex = data.url.lastIndexOf('}');
    const dynamicParam = data.url.slice(index + 1, lastIndex);
    data.url = data.url.substring(0, index);
    return `
/**
 * ${data.summary}
 */
get${firstUpperCase(lastWord.replace('{', '').replace('}', ''))}Api(${dynamicParam}) {
  return this.http.${data.method}('', \`\${this.preUrl}/\${${dynamicParam}}\`);
}
`;
  }
  return `
/**
 * ${data.summary}
 */
${hasGetWord(data)}${hasGetWord(data) ? generatorGroupName(data) : firstLowerCase(generatorGroupName(data))}Api(data) {
  return this.http.${data.method}(data, \`\${this.preUrl}${lastWord}\`);
}
`;
};

/**
 * 判断是否需要拼接get字段
 */
const hasGetWord = (data: any) => {
  if (data.summary.indexOf('获取') > -1) {
    return 'get';
  }
  if (data.method === 'get') {
    return 'get';
  }
  return '';
};

/**
 * 获取definitions
 */
const getDefinitionsMap = (definitions) => {
  for (const key in definitions) {
    definitionsMap[key] = definitions[key];
  }
};

/**
 * 获取schema
 */
const getSchemaMap = (paths) => {
  for (const key in paths) {
    summaryMap[key] = paths[key][getMethod(paths[key])].summary;
    if (paths[key][getMethod(paths[key])].parameters) {
      if (paths[key][getMethod(paths[key])].parameters) {
        paths[key][getMethod(paths[key])].parameters.map(item => {
          if (item.schema) {
            if (item.schema.$ref) {
              schemaMap[key] = item.schema.$ref.replace('#/definitions/', '');
            } else {
              schemaMap[key] = item.schema;
            }
          }
        });
      }
    }
  }
};

/**
 * 获取请求方式
 */
const getMethod = (map) => {
  let method = '';
  for (const key in map) {
    if (map.hasOwnProperty('get')) {
      method = 'get';
    }
    if (map.hasOwnProperty('post')) {
      method = 'post';
    }
  }
  return method;
};

/**
 * 获取url的最后一个单词
 */
const getLastPathWord = (url: string) => {
  const urlArr = url.split('/');
  return urlArr[urlArr.length - 1];
};

/**
 * 生成component.ts的方法参数
 */
const generatorInterfaceParam = (data: any, lastWord: string) => {
  if (!data.parameters) {
    return data.method === 'get' ? '\'\'' : '{}';
  }
  const param = Object.keys(data.parameters);
  if (param.length === 1 && param[0] === 'id') {
    return `{
      id: 'xxxxx'
    }`;
  }
  return `${data.parameters ? `${lastWord}: I${firstUpperCase(lastWord)}` : ''}`;
};


/**
 * 根据url生成groupName
 */
const generatorGroupName = (data: any) => {
  let groupWord = '';
  const arr = data.originUrl.split('/');
  const len = arr.length;
  arr.map((item, index) => {
    if (index >= 2 && index < len - 1) {
      groupWord += firstUpperCase(item);
    }
  });
  return firstUpperCase(arr[len - 1]) + groupWord;
};

/**
 * 获取url的2个最后单词
 */
const getUrlTwoLastWord = (data: any) => {
  const arr = data.originUrl.split('/');
  const len = arr.length;
  return firstUpperCase(arr[len - 2]) + firstUpperCase(arr[len - 1]);
};

/**
 * 生成component.ts的接口字段
 */
const generatorInterfaceField = (data: any) => {
  let i = 0;
  const len = Object.keys(data.parameters).length;
  let fieldCode = '';
  for (const o in data.parameters) {
    if (data.parameters[o].type === 'object') {
      fieldCode += `${o}: I${firstUpperCase(o)}; // ${data.parameters[o].title}\n  `;
      subInterfaceList.push({
        parameters: data.parameters[o].properties,
        field: o,
        title: data.parameters[o].title
      });
    } else {
      fieldCode += `${o}: ${endFieldMap(data.parameters[o].type, data.parameters[o])}; ${data.parameters[o].description ? `// ${data.parameters[o].description}` : ''}${i < len - 1 ? '\n  ' : ''}`;
    }
    i ++;
  }
  return fieldCode;
};


/**
 * 获取字段类型
 */
const endFieldMap = (type, fieldInfo) => {
  const map = {
    integer: 'number'
  };
  if (type === 'array') {
    return `Array<${fieldInfo.items.type}>`;
  }
  return map[type] || type;
};
